global.Promise = require('bluebird')
const request = Promise.promisifyAll(require('request'))
const {UserId, access_token} = require('./config.js')

const operationOrderGap = 100 
main()

async function main(base = process.argv[2]) {
	if (base) {
		await cancel(base)
		return
	}
	let Contracts = ['btc', 'ltc', 'bth', 'eth', 'etc', 'eos', 'ae', 'omg', 'loom', 'qash', 'iost', 'btm']
	for (let Contract of Contracts) {
		await cancel(Contract)
	}
}

async function cancel(base = process.argv[2]) {
	if (!base) return
	const orders = await listWaitOrders(`${base.toUpperCase()}_USD`)
	console.log(base, orders.length)
	for (let order of orders) {
		await cancelOrder(order.ClientOrderId)
	}
}

async function listWaitOrders(Contract) {
	const url = `https://www.chaobi.com:7443/rsporder/list?Contract=${Contract}&access_token=${access_token}&UserId=${UserId}`
	let {body} = await request.getAsync(url)
	body = JSON.parse(body)
	const orders = body.data || []
	// ["Received", "PartTradingQueueing", "AllTraded", "Canceled", "Error"]
	return orders.filter(item => item.OrderStatus == 'Received' || item.OrderStatus == 'PartTradingQueueing')
}

async function cancelOrder(ClientOrderId) {
	await Promise.delay(operationOrderGap)
	const url = 'https://www.chaobi.com:7443/order/cancel'
	const headers = { "content-type": "application/json"}
	const body = {access_token, UserId, ClientOrderId}
	let data = await request.postAsync(url, {headers, body, json: true})
	let status = data.body && data.body.status
	let message = data.body && data.body.message

	console.log(data.error, status, message)
}
